package cn.dgut.training.controller;


import cn.dgut.training.annotation.LoginUser;
import cn.dgut.training.dto.AddressDTO;
import cn.dgut.training.entity.Address;
import cn.dgut.training.service.impl.AddressServiceImpl;
import cn.dgut.training.service.impl.RegionServiceImpl;
import cn.dgut.training.service.impl.UserServiceImpl;
import cn.dgut.training.vo.CommonResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/address")
public class AddressController {

    @Resource
    private AddressServiceImpl addressService;

    @Resource
    private RegionServiceImpl regionService;

    @Resource
    private UserServiceImpl userService;


    /**
     * 增加或更新新地址
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public CommonResponse create(@LoginUser Long userId, @RequestBody AddressDTO addressDTO) {


        if (userId == null) {
            return CommonResponse.fail("请登录！");
        }
        addressDTO.setUserId(userId.intValue());


        Address address = new Address();
        BeanUtils.copyProperties(addressDTO, address);
        Long provinceId = regionService.getByName(0L, address.getProvince()).getId();
        Long cityId = regionService.getByName(provinceId, address.getCity()).getId();
        Long countyId = regionService.getByName(cityId, address.getCounty()).getId();
        address.setProvince(Long.toString(provinceId));
        address.setCity(Long.toString(cityId));
        address.setCounty(Long.toString(countyId));

        if (address.getIsDefault()) {
            List<Address> addressList = addressService.UniqueDefault(address.getIsDefault(), address.getUserId());
            for (Address address1 : addressList) {
                addressService.updateById(address1);
            }
        }
        addressService.saveOrUpdate(address);
        return CommonResponse.message();
    }


    /**
     * 删除地址
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public CommonResponse deleteById(@LoginUser Long userId, @RequestBody AddressDTO addressDTO) {

        if (userId == null) {
            return CommonResponse.fail("请登录！");
        }

        Address address = new Address();
        BeanUtils.copyProperties(addressDTO, address);

        addressService.removeById(address.getId());

        return CommonResponse.message();
    }


    /**
     * 修改地址
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public CommonResponse update(@LoginUser Long userId, @RequestBody AddressDTO addressDTO) {

        if (userId == null) {
            return CommonResponse.fail("请登录！");
        }

        Address address = new Address();
        BeanUtils.copyProperties(addressDTO, address);
        Long provinceId = regionService.getByName(0L, address.getProvince()).getId();
        Long cityId = regionService.getByName(provinceId, address.getCity()).getId();
        Long countyId = regionService.getByName(cityId, address.getCounty()).getId();
        address.setProvince(Long.toString(provinceId));
        address.setCity(Long.toString(cityId));
        address.setCounty(Long.toString(countyId));

        addressService.updateById(address);

        return CommonResponse.message();
    }


    /**
     * id查找地址
     * 也可以使用下方的select（）查询
     */
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public CommonResponse getById(@LoginUser Long userId, @Param("id") long id) {

        if (userId == null) {
            return CommonResponse.fail("请登录！");
        }

        Address address = addressService.getById(id);
        address.setProvince(regionService.getById(address.getProvince()).getName());
        address.setCity(regionService.getById(address.getCity()).getName());
        address.setCounty(regionService.getById(address.getCounty()).getName());

        return CommonResponse.success(address);
    }


    /**
     * 获取默认地址
     */
    @RequestMapping(value = "/default", method = RequestMethod.POST)
    public CommonResponse showDefaultAddress(@LoginUser Long userId, @RequestBody AddressDTO addressDTO) {

        if (userId == null) {
            return CommonResponse.fail("请登录！");
        }

        Address address = addressService.getDefault(addressDTO);
        address.setProvince(regionService.getById(address.getProvince()).getName());
        address.setCity(regionService.getById(address.getCity()).getName());
        address.setCounty(regionService.getById(address.getCounty()).getName());

        return CommonResponse.success(address);
    }


    /**
     * 微信端接口完成；
     * 根据 用户userId 或 收货人名称name 或 订单id 查询
     * 注意:根据单字段查询时，勿返回多个属性字段
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public CommonResponse listAddressByPage(@LoginUser Long userId, @RequestBody AddressDTO addressDTO) {


        if (userService.getById(userId).getUserLevel() == 1) {
            addressDTO.setUserId(userId.intValue());
        }

        List<Address> addressList = addressService.SelectAddress(addressDTO);

        for (Address address : addressList) {

            address.setProvince(regionService.getById(Long.parseLong(address.getProvince())).getName());
            address.setCity(regionService.getById(Long.parseLong(address.getCity())).getName());
            address.setCounty(regionService.getById(Long.parseLong(address.getCounty())).getName());
        }

        return CommonResponse.success(addressService.listByPage(addressList));
    }

    /**
     * 管理后台接口
     * @param addressDTO
     * @return
     */
    @RequestMapping(value = "/adminList", method = RequestMethod.POST)
    public CommonResponse adminListAddressByPage( @RequestBody AddressDTO addressDTO) {

        List<Address> addressList = addressService.SelectAddress(addressDTO);

        for (Address address : addressList) {

            address.setProvince(regionService.getById(Long.parseLong(address.getProvince())).getName());
            address.setCity(regionService.getById(Long.parseLong(address.getCity())).getName());
            address.setCounty(regionService.getById(Long.parseLong(address.getCounty())).getName());
        }

        return CommonResponse.success(addressService.listByPage(addressList));
    }

    /**
     * 购物车模块调用
     *
     * @param userId
     * @param
     * @return
     */
    @PostMapping("/iDefault")
    public Address iShowDefaultAddress(@RequestParam("userId") Long userId) {

        Address address = addressService.getOne(new QueryWrapper<Address>().lambda()
                .eq(Address::getUserId, userId)
                .eq(Address::getIsDefault, 1));
        if (address != null) {
            address.setProvince(regionService.getById(Long.parseLong(address.getProvince())).getName());
            address.setCity(regionService.getById(Long.parseLong(address.getCity())).getName());
            address.setCounty(regionService.getById(Long.parseLong(address.getCounty())).getName());
        }

        return address;
    }

    /**
     * 订单模块通过id查找地址
     *
     * @param id
     * @return
     */
    @PostMapping("/iDetail")
    public Address iGetById(@RequestParam("id") Long id) {

        Address address = addressService.getById(id);
        if (address != null) {
            address.setProvince(regionService.getById(Long.parseLong(address.getProvince())).getName());
            address.setCity(regionService.getById(Long.parseLong(address.getCity())).getName());
            address.setCounty(regionService.getById(Long.parseLong(address.getCounty())).getName());
        }

        return address;
    }

}
